﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using XChipTool.Enties;
using NPOI.HSSF.UserModel;
using XChip_Common;
using System.IO;
using NPOI.SS.UserModel;
using System.Globalization;
using NPOI.SS.Util;

namespace XChipTool
{
    public partial class XChip_RegMapping : DevExpress.XtraEditors.XtraUserControl
    {
        public addressregisterManager Addr_dal { get; set; }        
        int topIndex = -1;
        //private List<addressregister> ulist;//使用的 use
        public XChip_RegMapping()
        {
            InitializeComponent();
        }
        public XChip_RegMapping(addressregisterManager _Addr_dal)
        {
            Addr_dal = _Addr_dal;
            InitializeComponent();
        }

        private void XChip_RegMapping_Load(object sender, EventArgs e)
        {
            if (null != Addr_dal)
            {
              var  ulist = Addr_dal.GetList();
                gridControl1.DataSource = ulist;
                gridView1.RefreshData();
                gongnengEdit.Properties.DataSource = ulist.Select(c => c.Classify).Distinct().ToList();
                gongnengEdit.ItemIndex = -1;
            }
        }
       

        private void gongnengEdit_EditValueChanged(object sender, EventArgs e)
        {
            textEdit1.Text = null;           
            var aut = gongnengEdit.EditValue.ToString();
            gridControl1.DataSource = Addr_dal.GetList(c => c.Classify == aut).ToList(); 
            gridView1.RefreshData();
            simpleButton1.Enabled = false;
        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            var i=  this.gridView1.FocusedRowHandle;
            var addr = gridView1.GetRowCellDisplayText(i, gridView1.Columns["Address"]);
            var name = gridView1.GetRowCellDisplayText(i, gridView1.Columns["NameType"]);
            var classify = gridView1.GetRowCellDisplayText(i, gridView1.Columns["Classify"]);
            var type = gridView1.GetRowCellDisplayText(i, gridView1.Columns["ControlType"]);
            var note = gridView1.GetRowCellDisplayText(i, gridView1.Columns["Note"]);
            moduleLab.Text = classify;
            labelControl1.Text = type;
            labelControl9.Text = name;
            AddrTxt.Text = addr;
            NoteTxt.Text = note;
            labelControl10.Text = gridView1.GetRowCellDisplayText(i, gridView1.Columns["ID"]);
            simpleButton1.Enabled = true;
        }

        private void simpleButton1_Click(object sender, EventArgs e)//更新
        {
            addressregister model = new addressregister();
            if (string.IsNullOrEmpty(AddrTxt.Text)) return;
            model.ID = int.Parse(labelControl10.Text);
            model = Addr_dal.GetSingle(c => c.ID == model.ID);
                 //ulist.Where(c => c.ID == model.ID).First();
            if (model.Address != AddrTxt.Text || model.Note != NoteTxt.Text)
            {
                model.Address = AddrTxt.Text;
                model.Note = NoteTxt.Text;
                Addr_dal.Update(model);
                //gridControl1.DataSource = Addr_dal.GetList();
                //gridView1.RefreshData();
                newRefreshDate();
            }
        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)//查询
        {
            newRefreshDate();
            simpleButton1.Enabled = false;
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "ControlType")
            {
                if (e.Value == null) return;
                    if (e.Value.ToString() == "0")
                    {
                        e.DisplayText = "文本框";
                    }
                    if (e.Value.ToString() == "1")
                    {
                        e.DisplayText = "勾选框";
                    }
            }
        }

        private void newRefreshDate()
        {
            var curList = gridControl1.DataSource;
            if (string.IsNullOrEmpty(textEdit1.Text))//搜索为空
            {
                if (null == gongnengEdit.EditValue)//模块为空
                {
                    curList = Addr_dal.GetList();
                }
                else
                {
                    var aut = gongnengEdit.EditValue.ToString();
                    curList = Addr_dal.GetList(c => c.Classify == aut).ToList();

                }
            }
            else//搜索不为空
            {                
                curList = Addr_dal.GetList(c => c.Address.Contains(textEdit1.Text) || c.Classify.Contains(textEdit1.Text) || c.ControlType.Contains(textEdit1.Text) || c.NameType.ToLower().Contains(textEdit1.Text));
            }
            gridControl1.DataSource = curList;
            gridView1.RefreshData();           
            gridView1.TopRowIndex = topIndex;
            simpleButton1.Enabled = false;          
         }

        private void gridView1_TopRowChanged(object sender, EventArgs e)
        {
            topIndex = gridView1.TopRowIndex;
        }
        /// <summary>
        /// 导出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton7_Click(object sender, EventArgs e)
        {
            var ulist = Addr_dal.GetList();
            var sheetList = ulist.Select(c => c.Classify).Distinct().ToList();
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "导出文件（*.xls）|*.xls";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "寄存器_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK) {
                HSSFWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("说明文档");
                ICell cell = sheet.CreateRow(0).CreateCell(0);
                cell.SetCellValue(@"此表用于匹配调试工具页面显示的寄存器地址框，便于后期维护。
“NameType”栏：
1.0 单个寄存器 暂无无要求；
2.0 两位中的“xx_H”代表高位地址，“xx_L”代表低位地址；
3.0 多位，则“xx_L”代表永远最低位，“xx_M0”代表中间开始，“xx_M1...xx_M7”代表结束 “xx_H”代表永远最高位；
 示例：Factor_l->Factor_m0->Factor_m1->Factor_h ；
4.0 注意选项 勾选框 必须已 “_EN” 结束；
5.0 注意 Day、Night、Midnight 、normal、mono,
 示例1：Factor_day_l->Factor_day_m0->Factor_day_m1->Factor_day_h ；
 示例2：Factor_day_l->Factor_day_h ；
“bits”栏：
1.0 正确规范，勾选框参考范本：[0]、[1]、[2]、[3]、[4]、[5]、[6]、[7]
2.0 正确规范，文本框参考范本：、[15:8]、[7:0]、[4:2]、高位在前，低位在后；
3.0 注意选项：如果文本框或者勾选框范围给错，会影响正则判断、会影响输入框的位数。
“Bit_Wide”栏：
1.0 位宽，正确规范，同一名称控件需填写总的位宽数，示例：AE_target_H与AE_target_L都得填写为16；
“Bit_Accuracy”栏：
1.0 精度，按需填写；");
                
                sheet.AddMergedRegion(new CellRangeAddress(0, 35, 0, 0));
                sheet.SetColumnWidth(0, 50000);
                
                ICellStyle style = workbook.CreateCellStyle();
                style.VerticalAlignment = VerticalAlignment.Center;
                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                IFont font = workbook.CreateFont();
                font.FontHeight = 16 * 16;
                style.SetFont(font);
                style.WrapText = true;
                style.FillPattern = FillPattern.SolidForeground;
               
                cell.CellStyle = style;
                
                foreach (var sheetitem in sheetList)
                {
                    var pList = ulist.Where(c => c.Classify == sheetitem).OrderBy(c => c.Address).ToList();
                    DataTable dt = NPOIOprateExcel.ListToDataTable(pList);
                    dt.Columns.Remove("id");
                    dt.Columns.Remove("AddressPart");
                    dt.Columns.Remove("Hex");
                    dt.Columns.Remove("HighLow");
                    dt.Columns.Remove("ControlType");
                    dt.Columns.Remove("Sorting");
                    dt.Columns.Remove("Note");
                    dt.Columns.Remove("PreNote");
                    dt.Columns.Remove("Classify");
                    dt.Columns.Remove("ChipType");

                    createSheet(dt, true, workbook, sheetitem);
                }
                FileStream fs = new FileStream(sfd.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                workbook.Write(fs);
                fs.Close();
            }
            DevExpress.XtraEditors.XtraMessageBox.Show($"导出完成！");
        }
        private ISheet createSheet(DataTable data, bool isColumnWritten, HSSFWorkbook workBook, string sheetName)
        {

            int count = 0;
            ISheet sheet = workBook.CreateSheet(sheetName);
            if (isColumnWritten == true) //写入DataTable的列名
            {
                IRow row = sheet.CreateRow(0);
                for (int j = 0; j < data.Columns.Count; ++j)
                {
                    row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                }
                count = 1;
            }
            else
            {
                count = 0;
            }
            for (int i = 0; i < data.Rows.Count; ++i)
            {
                IRow row = sheet.CreateRow(count);
                for (int j = 0; j < data.Columns.Count; ++j)
                {
                    row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                }
                ++count;
            }

            return sheet;
        }

        /// <summary>
        /// 导入按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "导入文件（*.xls）|*.xls";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                var line = 0;
                var page = 0;
                try
                {
                    var fs = new FileStream(sfd.FileName, FileMode.Open, FileAccess.Read);
                    var workbook = new HSSFWorkbook(fs);
                    //var ulist = Addr_dal.GetList();
                    //var sheetList = ulist.Select(c => c.Classify).Distinct().ToList();
                    int SortNum = 0;
                    var SList = NPOIOprateExcel.GetSheetName(workbook);
                    int sort = 0;

                    for (int i = 0; i < SList.Count; i++)
                    {
                        if (SList[i].Contains("说明")) continue;
                       
                        page = i;
                        var sheetid = workbook.GetSheetIndex(SList[i]);
                        DataTable dt = NPOIOprateExcel.ExcelToDataTable(sfd.FileName, true, sheetid);
                        List<addressregister> peList = dt.ToList<addressregister>().OrderBy(c=>c.Sorting).ToList();
                        for (int j = 0; j < peList.Count(); j++)
                        {

                            if (peList[j].NameType.Contains("HDRmode"))
                            {

                            }
                            line = j;
                            peList[j].Sorting = j.ToString("#0000");
                            peList[j].Address = peList[j].Address.Replace("0x", "").Replace(".0", "").Replace(" ", "").ToUpper();
                            UInt32 wtf = 0;
                            bool isbool =   UInt32.TryParse(peList[j].Address, NumberStyles.HexNumber,CultureInfo.InvariantCulture, out wtf);
                            peList[j].AddressPart = ((wtf) >> 16).ToString("X4");
                            peList[j].ChipType = "xc151";
                            peList[j].Classify = SList[i];
                            //var pe =  peList[i].NameType.ToLower().Substring(peList[i].NameType.Length - 2, 2);
                            peList[j].ControlType = peList[j].NameType.ToLower().Substring(peList[j].NameType.Length - 2, 2).Contains("en") ? "1" : "0";

                            if (peList[j].ControlType == "1")
                            {
                                if (!string.IsNullOrEmpty(peList[j].Bits)&&peList[j].Bits.Contains("]") && peList[j].Bits.Contains("["))
                                {
                                    var bitsTemp = peList[j].Bits.Replace("[", "").Replace("]", "").Split(':');
                                    int max = bitsTemp.Max(c => int.Parse(c));
                                    string binary = "";
                                    for (int z = 7; z > -1; z--)
                                    {
                                        if (z == max)
                                        {
                                            binary += "1";
                                        }
                                        else
                                        {
                                            binary += "0";
                                        }
                                    }
                                    peList[j].Hex = string.Format("{0:X}", System.Convert.ToInt32(binary, 2));
                                }
                                
                            }
                            else {
                                if (!string.IsNullOrEmpty(peList[j].Bits) && peList[j].Bits.Contains("]") && peList[j].Bits.Contains("[")) {
                                    var bitsTemp = peList[j].Bits.Replace("[", "").Replace("]", "").Split(':');
                                    int max = bitsTemp.Max(c => int.Parse(c));
                                    int min = bitsTemp.Min(c => int.Parse(c));
                                    string binary = "";
                                    if (max == min&& max <=7)
                                    {
                                        for (int z = 7; z > -1; z--)
                                        {
                                            if (z == max)
                                            {
                                                binary += "1";
                                            }
                                            else
                                            {
                                                binary += "0";
                                            }
                                        }
                                        
                                    }
                                    else {
                                        for (int z = 0; z <= max - min; z++)
                                        {
                                            binary += "1";
                                        }
                                    }
                                    
                                    peList[j].Hex  = string.Format("{0:X}", System.Convert.ToInt32(binary, 2));
                                }
                            }
                        }
                        //加过滤条件
                        Addr_dal.Delete(c => c.Classify == SList[i]);
                        Addr_dal.Insert(peList);
                    }
                    DevExpress.XtraEditors.XtraMessageBox.Show($"导入完成！请手动重启软件");
                }
                catch (Exception ex)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show($"打开表格错误信息：{ex.Message.ToString()}{page},{line}");
                }
            }
        }
    }
}

